package com.example.elmspringboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.elmspringboot.controller.utils.BusinessDTO;
import com.example.elmspringboot.controller.utils.CartDto;
import com.example.elmspringboot.domain.Cart;
import com.example.elmspringboot.domain.Food;
import com.example.elmspringboot.mapper.CartMapper;
import com.example.elmspringboot.mapper.FoodMapper;
import com.example.elmspringboot.service.CartService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Resource
    private CartMapper cartMapper;

    @Resource
    private FoodMapper foodMapper;

    @Override
    public Boolean saveCart(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(true, Cart::getFoodId,cart.getFoodId())
                .eq(true, Cart::getShopId, cart.getShopId())
                .eq(true, Cart::getUserId, cart.getUserId());
        Cart cartOne = cartMapper.selectOne(wrapper);
        if(cartOne != null){
            QueryWrapper<Cart> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", cartOne.getId());
            if(cart.getQuantity()==0){
                cartMapper.deleteById(cartOne.getId());
                return true;
            }
            cartOne.setQuantity(cart.getQuantity());
            cartMapper.update(cartOne, wrapper1);
        }
        else {
            cartMapper.insert(cart);
        }
        return true;
    }

    @Override
    public List<CartDto> getCartFood(Integer userId, Integer shopId) {
        MPJLambdaWrapper<Cart> eq = new MPJLambdaWrapper<Cart>().select(Cart::getQuantity).select(Cart::getFoodId).select(Cart::getId).
                select(Food::getName).select(Food::getImgUrl).select(Food::getDescription).select(Food::getPrice).
                innerJoin(Food.class, Food::getId, Cart::getFoodId).
                eq(Cart::getShopId, shopId).eq(Cart::getUserId,userId);
        return cartMapper.selectJoinList(CartDto.class, eq);
    }
}
